<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Document</title>
	</head>
	<body>
		<div id="receiveMsg">接收消息</div>
		<input type="text" id="msgContent" />
		<input type="button" value="点我发送" onclick="Chat.chat()" />
		<script>
			window.Chat = {
				socket: null,
				init: function() {
					// 判断当前浏览器是否支持WebSocket
					if (window.WebSocket) {
						Chat.socket = new WebSocket("ws://192.168.98.109:8888/ws");
						Chat.socket.onopen = function() {
							console.log("连接建立成功！");
						};
						Chat.socket.onclose = function() {
							console.log("连接关闭！");
						};
						Chat.socket.onerror = function() {
							console.log("发生错误！");
						};
						Chat.socket.onmessage = function(e) {
							console.log("接收到消息：" + e.data);
							var receiveMsg = document.getElementById("receiveMsg");
							var html = receiveMsg.innerHTML;
							receiveMsg.innerHTML = html + e.data;
						};
					} else {
						alert("当前浏览器不支持WebSocket！");
					}
				},
				chat: function() {
					var msgContent = document.getElementById("msgContent");
					Chat.socket.send(msgContent.value);
				}
			}
			Chat.init();
		</script>
	</body>
</html>
